using Microsoft.Phone.Controls.Maps.PlatformServices;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Device.Location;
using System.Globalization;
using System.Net.NetworkInformation;
namespace Microsoft.Phone.Controls.Maps.Core
{
	public class CopyrightManager
	{
		private static CopyrightManager instance;
		private static readonly Dictionary<CultureInfo, string> defaultCopyrightCache = new Dictionary<CultureInfo, string>();
		private readonly Dictionary<CopyrightKey, List<CopyrightRequestState>> fetching = new Dictionary<CopyrightKey, List<CopyrightRequestState>>(new CopyrightKeyComparer());
		private readonly Dictionary<CopyrightKey, Collection<ImageryProvider>> imageryProviders = new Dictionary<CopyrightKey, Collection<ImageryProvider>>(new CopyrightKeyComparer());
		private readonly TimeSpan minimumRetryInterval = new TimeSpan(0, 2, 0);
		private readonly Dictionary<CopyrightKey, BadFetchState> retryFailedFetchAt = new Dictionary<CopyrightKey, BadFetchState>(new CopyrightKeyComparer());
		private ImageryServiceClient client;
		private ImageryServiceClient Client
		{
			get
			{
				return this.client;
			}
		}
		private CopyrightManager()
		{
			MapConfiguration.GetSection("v1", "WP7SLMapControl", null, new MapConfigurationCallback(this.AsynchronousConfigurationLoaded));
		}
		private void AsynchronousConfigurationLoaded(MapConfigurationSection config, object userState)
		{
			if (config != null && config.Contains("ImageryServiceUri"))
			{
				this.client = WebServicesUtility.CreateImageryServiceClient(config["ImageryServiceUri"]);
				this.client.GetImageryMetadataCompleted += new EventHandler<GetImageryMetadataCompletedEventArgs>(this.clientGetImageryMetadataCompleted);
			}
		}
		public static CopyrightManager GetInstance()
		{
			if (CopyrightManager.instance == null)
			{
				CopyrightManager.instance = new CopyrightManager();
			}
			return CopyrightManager.instance;
		}
		internal static CopyrightManager GetCleanInstance()
		{
			return new CopyrightManager();
		}
		private static string DefaultCopyright(CultureInfo culture)
		{
			if (!CopyrightManager.defaultCopyrightCache.ContainsKey(culture))
			{
				string text = string.Format(culture, CoreResources.DefaultCopyright, new object[]
				{
					DateTime.get_Now().get_Year()
				});
				CopyrightManager.defaultCopyrightCache.set_Item(culture, text);
			}
			return CopyrightManager.defaultCopyrightCache.get_Item(culture);
		}
		private IList<string> GetCopyrightStrings(CopyrightKey copyrightKey, GeoCoordinate location, double zoomLevel)
		{
			List<string> list = new List<string>();
			List<string> list2 = new List<string>();
			Collection<ImageryProvider> collection = this.imageryProviders.ContainsKey(copyrightKey) ? this.imageryProviders.get_Item(copyrightKey) : null;
			if (collection == null)
			{
				list.Add(CopyrightManager.DefaultCopyright(copyrightKey.Culture));
			}
			else
			{
				int num = (int)Math.Round(zoomLevel);
				using (IEnumerator<ImageryProvider> enumerator = collection.GetEnumerator())
				{
					while (enumerator.MoveNext())
					{
						ImageryProvider current = enumerator.get_Current();
						using (IEnumerator<CoverageArea> enumerator2 = current.CoverageAreas.GetEnumerator())
						{
							while (enumerator2.MoveNext())
							{
								CoverageArea current2 = enumerator2.get_Current();
								RangeOfint zoomRange = current2.ZoomRange;
								if (zoomRange.From <= num && num <= zoomRange.To)
								{
									Rectangle boundingRectangle = current2.BoundingRectangle;
									if (boundingRectangle.Southwest.Latitude <= location.get_Latitude() && location.get_Latitude() <= boundingRectangle.Northeast.Latitude && boundingRectangle.Southwest.Longitude <= location.get_Longitude() && location.get_Longitude() <= boundingRectangle.Northeast.Longitude)
									{
										if (current.Attribution.get_Chars(0) == '©')
										{
											list.Add(current.Attribution);
										}
										else
										{
											list2.Add(current.Attribution);
										}
										break;
									}
								}
							}
						}
					}
				}
			}
			list.AddRange(list2);
			return list;
		}
		private void SetFetchFailed(CopyrightKey copyrightKey, CopyrightRequestState requestState, bool failed)
		{
			if (failed)
			{
				this.retryFailedFetchAt.set_Item(copyrightKey, new BadFetchState(DateTime.get_Now() + this.minimumRetryInterval, requestState.Credentials, requestState.Location));
				return;
			}
			if (this.retryFailedFetchAt.ContainsKey(copyrightKey))
			{
				this.retryFailedFetchAt.Remove(copyrightKey);
			}
		}
		private bool ReadyToFetch(CopyrightKey copyrightKey, CopyrightRequestState requestState)
		{
			if (this.Client == null)
			{
				return false;
			}
			if (!this.retryFailedFetchAt.ContainsKey(copyrightKey))
			{
				return true;
			}
			BadFetchState badFetchState = this.retryFailedFetchAt.get_Item(copyrightKey);
			return DateTime.get_Now() >= badFetchState.TryAgainAt || requestState.Credentials != badFetchState.CredentialsLastUsed;
		}
		internal void RequestCopyrightString(Microsoft.Phone.Controls.Maps.MapStyle style, GeoCoordinate location, double zoomLevel, CredentialsProvider credentialsProvider, CultureInfo culture, Action<CopyrightResult> copyrightCallback)
		{
			if (credentialsProvider != null)
			{
				credentialsProvider.GetCredentials(delegate(Microsoft.Phone.Controls.Maps.Credentials credentials)
				{
					this.RequestCopyrightString(style, location, zoomLevel, credentials, culture, copyrightCallback);
				});
				return;
			}
			Microsoft.Phone.Controls.Maps.Credentials credentials2 = null;
			this.RequestCopyrightString(style, location, zoomLevel, credentials2, culture, copyrightCallback);
		}
		private void RequestCopyrightString(Microsoft.Phone.Controls.Maps.MapStyle style, GeoCoordinate location, double zoomLevel, Microsoft.Phone.Controls.Maps.Credentials credentials, CultureInfo culture, Action<CopyrightResult> copyrightCallback)
		{
			bool flag = DesignerProperties.get_IsInDesignTool() || !NetworkInterface.GetIsNetworkAvailable();
			CopyrightKey copyrightKey = new CopyrightKey(culture, style);
			CopyrightRequestState copyrightRequestState = new CopyrightRequestState(culture, style, location, zoomLevel, credentials, copyrightCallback);
			if (flag || !this.ReadyToFetch(copyrightKey, copyrightRequestState))
			{
				List<string> list = new List<string>();
				list.Add(CopyrightManager.DefaultCopyright(culture));
				copyrightCallback.Invoke(new CopyrightResult(list, culture, location, zoomLevel));
				return;
			}
			if (this.imageryProviders.ContainsKey(copyrightKey))
			{
				copyrightCallback.Invoke(new CopyrightResult(this.GetCopyrightStrings(copyrightKey, location, zoomLevel), culture, location, zoomLevel));
				return;
			}
			if (this.fetching.ContainsKey(copyrightKey))
			{
				this.fetching.get_Item(copyrightKey).Add(copyrightRequestState);
				return;
			}
			List<CopyrightRequestState> list2 = new List<CopyrightRequestState>();
			list2.Add(copyrightRequestState);
			this.fetching.Add(copyrightKey, list2);
			ImageryMetadataRequest imageryMetadataRequest = new ImageryMetadataRequest();
			imageryMetadataRequest.Culture = culture.get_Name();
			switch (style)
			{
			case Microsoft.Phone.Controls.Maps.MapStyle.Road:
				IL_CF:
				imageryMetadataRequest.Style = Microsoft.Phone.Controls.Maps.PlatformServices.MapStyle.Road;
				goto IL_EB;
			case Microsoft.Phone.Controls.Maps.MapStyle.Aerial:
				imageryMetadataRequest.Style = Microsoft.Phone.Controls.Maps.PlatformServices.MapStyle.Aerial;
				goto IL_EB;
			case Microsoft.Phone.Controls.Maps.MapStyle.AerialWithLabels:
				imageryMetadataRequest.Style = Microsoft.Phone.Controls.Maps.PlatformServices.MapStyle.AerialWithLabels;
				goto IL_EB;
			}
			goto IL_CF;
			IL_EB:
			imageryMetadataRequest.Options = new ImageryMetadataOptions();
			imageryMetadataRequest.Options.ReturnImageryProviders = true;
			imageryMetadataRequest.ExecutionOptions = new ExecutionOptions();
			imageryMetadataRequest.ExecutionOptions.SuppressFaults = true;
			if (credentials != null)
			{
				imageryMetadataRequest.Credentials = new Microsoft.Phone.Controls.Maps.PlatformServices.Credentials
				{
					ApplicationId = credentials.ApplicationId
				};
			}
			this.Client.GetImageryMetadataAsync(imageryMetadataRequest, copyrightRequestState);
		}
		private void clientGetImageryMetadataCompleted(object sender, GetImageryMetadataCompletedEventArgs e)
		{
			bool flag = false;
			CopyrightRequestState copyrightRequestState = e.get_UserState() as CopyrightRequestState;
			CopyrightKey copyrightKey = new CopyrightKey(copyrightRequestState.Culture, copyrightRequestState.Style);
			try
			{
				bool flag2 = e.get_Error() == null && e.Result != null && e.Result.Results != null && e.Result.Results.get_Count() > 0;
				this.SetFetchFailed(copyrightKey, copyrightRequestState, !flag2);
				if (flag2)
				{
					this.imageryProviders.set_Item(copyrightKey, e.Result.Results.get_Item(0).ImageryProviders);
				}
				List<CopyrightRequestState> list = new List<CopyrightRequestState>(this.fetching.get_Item(copyrightKey));
				flag = this.fetching.Remove(copyrightKey);
				using (List<CopyrightRequestState>.Enumerator enumerator = list.GetEnumerator())
				{
					while (enumerator.MoveNext())
					{
						CopyrightRequestState current = enumerator.get_Current();
						current.CopyrightCallback.Invoke(new CopyrightResult(this.GetCopyrightStrings(copyrightKey, current.Location, current.ZoomLevel), current.Culture, current.Location, current.ZoomLevel));
					}
				}
			}
			finally
			{
				if (!flag)
				{
					this.fetching.Remove(copyrightKey);
				}
			}
		}
	}
}
